package com.bt.mes.common.excel.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Generates excel by the post JSON data.
 * 
 * @author Mxl
 *
 */
public class GenerateExcelServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public GenerateExcelServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
	        IOException {
		
		request.setCharacterEncoding("UTF-8");
		String data = request.getParameter("data");
		ObjectMapper om = new ObjectMapper();
		String[][] matrix = om.readValue(data, String[][].class);
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();
		for (int i = 0; i < matrix.length; i++) {
			HSSFRow row = sheet.createRow(i);
			for (int j = 0; j < matrix[i].length; j++) {
				HSSFCell cell = row.createCell(j);
				cell.setCellValue(matrix[i][j]);
			}
		}
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		workbook.write(baos);
		baos.flush();
		baos.close();
		response.reset();
		response.addHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".xls");
		response.addHeader("Content-Length", String.valueOf(baos.size()));
		response.setContentType("application/vnd.ms-excel");
		response.getOutputStream().write(baos.toByteArray());
	}

}
